package com.google.code.synchronized_player;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

import android.content.Context;
import android.util.Log;

public class PlayList {
	private MainActivity.Player player;
	private ArrayList<Track> tracks = new ArrayList<Track>();
	private ArrayList<String> sourceFolders = new ArrayList<String>();
	private String playListPath;
	private int currentTrackNumber = 0;
	private int trackPosition = 0;
	
	public PlayList(Context context, MainActivity.Player player) {
		this.player = player;
		File cacheDir;
		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            cacheDir = context.getCacheDir();//new File(android.os.Environment.getExternalStorageDirectory(),"vk.messenger");
		} else {
            cacheDir = context.getCacheDir();
		}
        if(!cacheDir.exists())
            cacheDir.mkdirs();
        File playListFile = new File(cacheDir, "playlist.m3u");
        playListPath = playListFile.getAbsolutePath();
        if(!playListFile.exists()) {
        	writePlayList();
        }
        readPlayList();
        Log.d("PlayList", cacheDir.getPath());
	}
	
	public void importFromString(String currentTrackNumber, String Position, String[] hashes) {
		Log.d("SynchronizedPlayer", "importFromString");
		int neededPosition = Integer.parseInt(currentTrackNumber);
		HashMap<String, String> paths = new HashMap<String, String> ();
		for(int i = 0; i < sourceFolders.size(); ++i) {
			File dir = new File(sourceFolders.get(i));
			File list[] = dir.listFiles();
			for(File f: list) if(f.isFile()) {
				Track currentTrack = new Track(f.getAbsolutePath());
				paths.put(currentTrack.getHash(), currentTrack.getPath());
				Log.d("PlayList", "Put (" + currentTrack.getHash() + ", " + currentTrack.getPath());
			}
		}
		tracks.clear();
		this.currentTrackNumber = -1;
		this.trackPosition = -1;
		for(int i = 0; i < hashes.length; ++i) {
			Log.d("PlayList", "Finding " + hashes[i]);
			if(paths.containsKey(hashes[i])) {
				Log.d("PlayList", "Founded " + hashes[i]);
				if(i >= neededPosition && this.currentTrackNumber < neededPosition) {
					this.currentTrackNumber = i;
					if(i == neededPosition) {
						this.trackPosition = (int)(1000 * Double.parseDouble(Position));
						Log.d("PLayList", "Pos:" + Double.toString(this.trackPosition));
					}
				}
				String path = paths.get(hashes[i]);
				tracks.add(new Track(path));
			}
		}
		if(this.currentTrackNumber == -1) {
			this.currentTrackNumber = 0;
			this.trackPosition = 0;
		}
		writePlayList();
		player.initTrack();
	}
	
	public String exportToString() {
		String res = Integer.toString(currentTrackNumber) + " " + Integer.toString(trackPosition) + " ";
		for(int i = 0; i < tracks.size(); ++i) {
			res += tracks.get(i).getHash() + " ";
		}
		return res;
	}
	
	public int size() {
		return tracks.size();
	}
	
	public final ArrayList<Track> getTracksList() {
		return tracks;
	}
	
	public final Track getTrack(int position) {
		if(position < 0 || position >= tracks.size())
			return null;
		return tracks.get(position);
	}
	
	public int getCurrentTrackNumber() {
		if(currentTrackNumber < 0 || currentTrackNumber >= tracks.size())
			currentTrackNumber = 0;
		return currentTrackNumber;
	}
	
	public final Track getCurrentTrack() {
		return getTrack(getCurrentTrackNumber());
	}
	
	public void setCurrentTrackNumber(int currentTrackNumber) {
		this.currentTrackNumber = currentTrackNumber; 
	}
	
	public boolean prevTrack() {
		if(currentTrackNumber > 0) {
			--currentTrackNumber;
			trackPosition = 0;
			return true;
		}
		return false;
	}
	
	public boolean nextTrack() {
		if(currentTrackNumber + 1 < tracks.size()) {
			++currentTrackNumber;
			trackPosition = 0;
			return true;
		}
		return false;
	}
	
	public int getTrackPosition() {
		return trackPosition;
	}
	
	public void setTrackPosition(int trackPosition) {
		this.trackPosition = trackPosition;
	}
	
	void addTrack(String path) {
		tracks.add(new Track(path));
		writePlayList();
	}

	void removeTrack(String path) {
		for(int i = 0; i < tracks.size(); ++i) {
			if(tracks.get(i).getPath().equals(path)) {
				tracks.remove(i);
			}
		}
		writePlayList();
	}
	
	private void readPlayList() {
		try {
			Scanner sc = new Scanner(new File(playListPath));
			sc.nextLine();
			while(sc.hasNext()) {
				sc.nextLine();
				String trackname = sc.nextLine();
				tracks.add(new Track(trackname));
			}
			sc.close();
		} catch(Exception fnfex) {
			Log.d("PlayList", "Wrong playlist");			
		}
	}
	
	public void writePlayList() {
		writePlayList(playListPath);
	}
	
	public void writePlayList(String path) {
		try {
			Log.d("PlayList", "savingPlayList " + path);
			FileWriter outStream = new FileWriter(path);
			outStream.write("#EXTM3U\n");
			for(Track cur: tracks) {
				outStream.write("#" + cur.getHash() + "\n");
				outStream.write(cur.getPath() + "\n");
			}
			outStream.close();
		} catch(IOException ioex) {
			Log.d("PlayList", "IO exception:" + ioex.getMessage());
		}
	}

	public void addSourceFolder(String path) {
		sourceFolders.add(path);
	}
}
